# encoding: utf-8
# Model for handling user authentication
class User < ActiveRecord::Base
  attr_accessible :name
  validates_uniqueness_of :name
  #TODO confirm username format
  validates :name, :format => /\A[\w]+\z/
  
  # Authenticates the user against NLS WFS and WMS APIs
  # * *Args*
  #   - +user+ -> API username
  #   - +pass+ -> API password
  # * *Returns*
  #   - User object if the authentication is successful
  #   - nil if the authentication is not successful
  #
  def self.authenticate(user, pass)
    auth = {:username => user, :password => pass}
    rasteri = HTTParty.get('https://ws.nls.fi/rasteriaineistot/', :basic_auth => auth)
    nimisto = HTTParty.get('https://ws.nls.fi/nimisto/', :basic_auth => auth)
    if (rasteri.code == 200 && nimisto.code == 200)
      User.find_by_name(user) || User.create!({:name => user})
    else
      return nil
    end
  end
  
end
